<?php

/**
 *  机型价格趋势
*/
namespace app\admin\service;
use app\admin\model\SellerInfo as ModelSellerInfo;
use app\admin\model\SellerInfo;
use app\admin\model\SellerPriceRecords as ModelSellerPriceRecords;
use app\facade\Basic;

class SellerProductPrice extends BaseService
{

    /**
     *   获取枚举
     */
    public function getEnum($param)
    {
        $ModelSellerProduct = new ModelSellerPriceRecords();
        $result = $ModelSellerProduct->getFieldEnum($param['field']);
        return Basic::data(0,'ok',$result);
    }

    /**
     * 获取机型列表
     */
    public function getList($param)
    {

        $where = [];
        /* 时间区间 */
        if (!empty($param['start_date']) && !empty($param['end_date'])) {

            $startDate = new \DateTime($param['start_date']);
            $endDate = new \DateTime($param['end_date']);
            $interval = $startDate->diff($endDate);

            /* 限制查询一年 */
            if ($interval->y >= 1) {
                return Basic::data(1, '时间范围不能超过一年');
            }

            $where[] = ['create_time','between', [$param['start_date'], $param['end_date']]];
        }

        /* 矿机型号 */
        if ( !empty($param['model_id']) ) {
            $where[] = ['model_id','=', $param['model_id']];
        }


        /* 渠道商类型 1 - 供应商 2 - 零售商 */
        if ( !empty($param['seller_category']) ) {
            $where[] = ['seller_category','=', $param['seller_category']];
        }

        /* 库存状态  instock - 在售； outofstock - 无货下架；presale - 预售 */
        if ( !empty($param['inventory_status']) ) {
            $where[] = ['inventory_status','=', $param['inventory_status']];
        }

        /* inventory_status如果是预售 则存储预售时间 */
        if ( !empty($param['presale_time']) ) {
            $where[] = ['presale_time','=', $param['presale_time']];
        }

        /* 状态 1 - 有效 0 - 无效 */
        if ( !empty($param['status']) ) {
            $where[] = ['status','=', $param['status']];
        }

        if ( !empty($param['seller_id'])) {
            $seller_ids = explode(',',$param['seller_id']);
            if (count($seller_ids) == 1) {
                $where[] = ['seller_id','=', $seller_ids[0]];
            }else {
                $where[] = ['seller_id','in', $seller_ids];
            }
        }

        /* 查询 */
        $result = ModelSellerPriceRecords::with([
            'seller_name' => function($query){
                return $query->field('id,name');
            },
            'model_name' => function ($query) {
                return $query->field('id,model_name');
            }
        ])->where($where)
            ->field('id,seller_id,model_id,price,price_unit,seller_category,price_category,inventory_status,presale_time,create_time,status')
            ->order('id','desc')
            ->paginate([
                'list_rows'=> $param['pageSize'],
                'var_page' => 'pageIndex',
            ]);

        $data = $result->toArray();

        foreach ( $data['data'] as $key => $value ) {

            /* 供应商 */
            if (!empty($data['data'][$key]['seller_name'])) {
                $data['data'][$key]['seller_name'] = $value['seller_name']['name'];
            } else {
                $data[$key]['seller_name'] = '';
            }

            /* 模型名称 */
            if (!empty($data['data'][$key]['model_name'])) {
                $data['data'][$key]['model_name'] = $value['model_name']['model_name'];
            } else {
                $data[$key]['seller_name'] = '';
            }
        }

        return Basic::paginator(0, 'ok', $data);
    }


    /**
     *  getTrend
    */
    public function getTrend($param)
    {
        /* 无查询条件 */
        if ( empty($param['start_date']) || empty($param['end_date']) || empty($param['model_id'])) {
            $data['type'] = 'line';
            $data['data'] = [];
            return Basic::data(0, 'ok', $data);
        }

        $where = [];

        /* 时间区间 */
        $startDate = new \DateTime($param['start_date']);
        $endDate = new \DateTime($param['end_date']);
        $interval = $startDate->diff($endDate);
        $days = $interval->days;

//        /* 限制查询一年 */
//        if ($interval->y >= 1) {
//            return Basic::data(1, '时间范围不能超过一年');
//        }


        $where[] = ['create_time','between', [$param['start_date'], $param['end_date']]];

        /* 矿机型号 */
        $where[] = ['model_id','=', $param['model_id']];


        /* 库存类型 */
        if ( !empty($param['inventory_status']) ) {
            $where[] = ['inventory_status','=', $param['inventory_status']];
        }

        /* 预售时间 */
        if ( !empty($param['presale_start_date']) && !empty($param['presale_end_date']) ) {
            $where[] = ['presale_time','between', [$param['presale_start_date'], $param['presale_end_date']]];
        }


        /* 经销商 */
        $data = [];
        if ( !empty($param['seller_id'])) {
            $seller_ids = explode(',',$param['seller_id']);
            if (count($seller_ids) == 1) {
                $data['type'] = 'line';
                $where[] = ['seller_id','=', $seller_ids[0]];
            }else {
                $data['type'] = 'candlestick';
                $where[] = ['seller_id','in', $seller_ids];
            }
        } else {
//            $data['type'] = 'candlestick';
        }

//        /* 折线图 */
//        if ( $data['type'] == 'line') {
//            $data['data'] = $this->getLineData($param,$where,$days);
//        }

        $data['type'] = 'candlestick';

        /*  K线图 */
        if ( $data['type'] == 'candlestick' ) {
            $data['data'] = $this->getKlineData($param,$where,$days);
        }

        return Basic::data(0, 'ok', $data);
    }

    /**
     *  getTrendList
     */
    public function getTrendList($param)
    {
        /* 无查询条件 */
        if ( empty($param['model_id'])) {
            return Basic::data(0, 'ok', []);
        }
        $where = [];
        /* 矿机型号 */
        $where[] = ['model_id','=', $param['model_id']];
        /* 库存类型 */
        if ( !empty($param['inventory_status']) ) {
            $where[] = ['inventory_status','=', $param['inventory_status']];
        }
        /* 预售时间 */
        if ( !empty($param['presale_start_date']) && !empty($param['presale_end_date']) ) {
            $where[] = ['presale_time','between', [$param['presale_start_date'], $param['presale_end_date']]];
        }
        /* 经销商 */
        if ( !empty($param['seller_id'])) {
            $seller_ids = explode(',',$param['seller_id']);
            $where[] = ['seller_id','in', $seller_ids];
        }
        $startTime = date('Y-m-d 00:00:00', strtotime('-7 days'));
        $endTime = date('Y-m-d H:i:s'); // 当前时间
        $list = ModelSellerPriceRecords::where($where)
            ->field('seller_id,price,price_unit,create_time')
            ->whereBetweenTime('create_time', $startTime,$endTime)->order('price asc')->select()->toArray();
        if(empty($list)){
            return Basic::data(0, 'ok', []);
        }
        $ids = array_column($list,'seller_id');
        $seller = SellerInfo::where('id','in',$ids)->field('id,name')->select()->toArray();
        $seller = array_column($seller,null,'id');
        foreach ($list as &$v){
            $v['seller_name'] = $seller[$v['seller_id']]['name']??'';
        }
        return Basic::data(0, 'ok', $list);
    }
    /**
     *  获取折线图数据
    */
    private function getLineData($param,$where,$days)
    {
        $where['status'] = 1;

        /* 查询 */
        $SelleName = ModelSellerInfo::where('id',$param['seller_id'])->value('name');

        $date_line = [];
        $i = 0;
        while( $i <= ($days) ) {
            $date_line[] = date("Y-m-d",strtotime($param['start_date']." +".$i." day"));
            $i++;
        }

        /* 售价 */
        $salesPrices_res = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',1)
            ->field('id,price,price_unit,price_category,create_time')->select();

        $salesPrices = [];
        if ( $salesPrices_res ) {
            $salesPrices = $salesPrices_res->toArray();
        }


        /* 售价 */
        $offer_data = [];
        foreach ( $date_line as $value ) {
            $item = '0.00';
            foreach ($salesPrices as $salesPricesValue) {
                if( $value == date("Y-m-d",strtotime($salesPricesValue['create_time'])) ) {
                    $item = $salesPricesValue['price'];
                    break;
                }
            }
            $offer_data[] = $item;
        }


        $data_value[] = [
            'name'=> $value,
            'type' =>  'line',
            'lineStyle' => [
                'color' => 'red'
            ],
            'data'=> $offer_data
        ];


        /* 报价 */
        $quotes_res = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',2)
            ->field('id,price,price_unit,price_category,create_time')->select();


        $quotes = [];
        if ( $quotes_res ) {
            $quotes = $quotes_res->toArray();
        }


        $cash_data = [];
        foreach ( $date_line as $value ) {
            $item = '0.00';
            foreach ($quotes as $quotesValue) {
                if( $value == date("Y-m-d",strtotime($quotesValue['create_time'])) ) {
                    $item = $quotesValue['price'];
                    break;
                }
            }
            $cash_data[] = $item;
        }



        $data_value[] = [
            'name'=> $value,
            'type' =>  'line',
            'lineStyle' => [
                'color' => 'green'
            ],
            'data'=> $cash_data
        ];


        // 获取最大值和最小值
        $offerMax = array_filter($offer_data, function($value) {
            return $value != 0.00;
        });

        if ( count($offerMax) > 0 ){
            $offerMax = max($offerMax);
        } else {
            $offerMax = 0;
        }

        $offerMin = array_filter($offer_data, function($value) {
            return $value != 0.00;
        });
        if ( count($offerMin) > 0) {
            $offerMin = min($offerMin);
        } else {
            $offerMin = 0;
        }

        // 获取最大值和最小值的下标
        $offerMaxIndex = array_search($offerMax, $offer_data);
        $offerMinIndex = array_search($offerMin, $offer_data);

        $cashMax = array_filter($cash_data, function($value) {
            return $value != 0.00;
        });




        if ( count($cashMax) > 0 ){
            $cashMax = max($cashMax);
        } else {
            $cashMax = 0;
        }


        $cashMin = array_filter($cash_data, function($value) {
            return $value != 0.00;
        });



        if ( count($cashMin) > 0) {
            $cashMin = min($cashMin);
        } else {
            $cashMin = 0;
        }

        $cashMaxIndex = array_search($cashMax, $cash_data);
        $cashMinIndex = array_search($cashMin, $cash_data);

        $statistics = [
            ['最大售价',( $offerMax != 0 ) ? $offerMax : '--',($offerMax != 0 ) ? $SelleName : '--',($offerMax != 0 ) ? $date_line[$offerMaxIndex] : '--'],
            ['最小售价',( $offerMin != 0 ) ? $offerMin : '--',($offerMin != 0 ) ? $SelleName : '--',($offerMin != 0 ) ? $date_line[$offerMinIndex] : '--'],
            ['最大报价',( $cashMax != 0 ) ? $cashMax : '--',($cashMax != 0 ) ? $SelleName : '--',($cashMax != 0 ) ? $date_line[$cashMaxIndex] : '--'],
            ['最小报价',( $cashMin != 0 ) ? $cashMin : '--',( $cashMin != 0 ) ? $SelleName : '--',( $cashMin != 0 ) ? $date_line[$cashMinIndex] : '--'],
        ];

        return [
            'data'=>$data_value,
            'date_line'=> array_values($date_line),
            'statistics' => $statistics
        ];
    }


    /**
     *  获取K线图数据
    */
    private function getKlineData($param,$where,$days)
    {

        $where['status'] = 1;
        $date_line = [];
        $i = 0;
        while( $i <= ($days) ) {
            $date_line[] = date("Y-m-d",strtotime($param['start_date']." +".$i." day"));
            $i++;
        }

        $data = [];
        $result_offer = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',1)
            ->field('create_time, MAX(price) as max_price , MIN(price) as min_price')
            ->group('create_time')
            ->select()->toArray();


        $result_cash = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',2)
            ->field('create_time, MAX(price) as max_price , MIN(price) as min_price')
            ->group('create_time')
            ->select()->toArray();

        $data['offer_data'] = [];
        foreach ( $date_line as $value ) {
            $item = ['0.00','0.00','0.00','0.00'];
            foreach ($result_offer as $offerValue) {
                if( $value == date("Y-m-d",strtotime($offerValue['create_time'])) ) {
                    $item = [$offerValue['min_price'],$offerValue['max_price'],$offerValue['min_price'],$offerValue['max_price']];
                    break;
                }
            }
            $data['offer_data'][] = $item;
        }


        $data['cash_data'] = [];
        foreach ( $date_line as $value ) {
            $item = ['0.00','0.00','0.00','0.00'];
            foreach ($result_cash as $cashValue) {
                if( $value == date("Y-m-d",strtotime($cashValue['create_time'])) ) {
                    $item = [$cashValue['min_price'],$cashValue['max_price'],$cashValue['min_price'],$cashValue['max_price']];
                    break;
                }
            }
            $data['cash_data'][] = $item;
        }

        $data['offer_date_line'] = $date_line;
        $data['cash_date_line'] = $date_line;


        /* 售价 */
        $res_1 = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',1)
            ->order('price', 'desc')
            ->field('id,price,seller_id,create_time')
            ->limit(1)
            ->find();


        $statistics = [];
        $item = [];
        if ($res_1 ) {
            $item[] = '最大售价';
            $item[] = $res_1->price;
            $item[] = $res_1->seller_id;
            $item[] = $res_1->create_time;
        } else {
            $item[] = '最大售价';
            $item[] = '--';
            $item[] = '';
            $item[] = '--';
        }

        $statistics[] = $item;

        $res_2 = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',1)
            ->order('price', 'esc')
            ->field('id,price,seller_id,create_time')
            ->limit(1)
            ->find();
        $item = [];
        if ( $res_2 ) {
            $item[] = '最小售价';
            $item[] = $res_2->price;
            $item[] = $res_2->seller_id;
            $item[] = $res_2->create_time;
        } else {
            $item[] = '最小售价';
            $item[] = '--';
            $item[] = '';
            $item[] = '--';
        }

        $statistics[] = $item;

        $res_3 = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',2)
            ->order('price', 'desc')
            ->field('id,price,seller_id,create_time')
            ->limit(1)
            ->find();
        $item = [];
        if ($res_3 ) {
            $item[] = '最大报价';
            $item[] = $res_3->price;
            $item[] = $res_3->seller_id;
            $item[] = $res_3->create_time;
        } else {
            $item[] = '最大报价';
            $item[] = '--';
            $item[] = '';
            $item[] = '--';
        }

        $statistics[] = $item;

        $res_4 = ModelSellerPriceRecords::where($where)
            ->where('price_category','=',2)
            ->order('price', 'esc')
            ->field('id,price,seller_id,create_time')
            ->limit(1)
            ->find();

        $item = [];
        if ($res_4 ) {
            $item[] = '最小报价';
            $item[] = $res_4->price;
            $item[] = $res_4->seller_id;
            $item[] = $res_4->create_time;
        } else {
            $item[] = '最小报价';
            $item[] = '--';
            $item[] = '';
            $item[] = '--';
        }

        $statistics[] = $item;
        $ids = array_column($statistics,2);
        $seller_ids = array_unique(array_filter($ids));

        $seller_list = [];
        if ( $seller_ids ) {
            $seller_list = ModelSellerInfo::where('id','in',$seller_ids)
                ->field('id,name')
                ->select()->toArray();
            $seller_list = array_column($seller_list,'name','id');
        }

        foreach ( $statistics as $key => $value ) {
            $statistics[$key][2] = $seller_list[$value[2]] ?? '--';
        }

        $data['statistics'] = $statistics;
        return $data;
    }

}
